<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item>资产管理</a-breadcrumb-item>
        <a-breadcrumb-item><router-link to="/property/plan">资产盘点计划</router-link></a-breadcrumb-item>
        <a-breadcrumb-item><a @click="goback">{{ name }}</a></a-breadcrumb-item>
        <a-breadcrumb-item>新增盘点子计划</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <a-form :form="form">
        <a-form-item label="盘点总计划" v-bind="formItemLayout">
          <!-- <a-input readonly :value="name" /> -->
          <span>{{ name }}</span>
        </a-form-item>
        <a-form-item label="盘点子计划名称" v-bind="formItemLayout">
          <a-input
            v-decorator="[
              'name',
              { rules: [{ required: true, message: '请输入子计划名称', whitespace: true }] },
            ]"
            placeholder="请输入子计划名称"
          />
        </a-form-item>
        <a-form-item label="核对截止日期" v-bind="formItemLayout">
          <a-date-picker
            v-decorator="[
              'deadline',
              { rules: [{ required: true, message: '请选择核对截止日期' }] },
            ]"
            placeholder="请选择核对截止日期"
          />
        </a-form-item>
      </a-form>

      <div>
        <span class="success-link" @click="handleAdd">新增区域</span>
        <a-table
          class="s-table"
          bordered
          :columns="columns"
          :data-source="list"
          :locale="{ emptyText: '请新增区域' }"
          :pagination="false"
          row-key="id"
        >
          <template slot="deptId" slot-scope="text,item">
            <a-select
              v-show="item.editable"
              v-model="item.deptId"
              placeholder="请选择区域"
              style="width: 150px"
            >
              <a-select-option
                v-for="area in areaList"
                :key="area.id"
                :value="area.id"
              >{{ area.name }}</a-select-option>
            </a-select>
            <span v-show="!item.editable">{{ $get(areaMaps, `${text}.name`, '无') }}</span>
          </template>
          <template slot="userId" slot-scope="text,item">
            <span
              v-if="item.deptId"
              style="cursor: default"
            >{{ $get(teacherMaps, `${$get(areaMaps, `${item.deptId}.userId`)}.name`, '请切换区域') }}</span>
            <span v-else>请选择区域</span>
            <!-- <a-cascader
              v-show="item.editable"
              v-model="item.userId"
              :disabled="!item.deptId"
              not-found-content="没有数据"
              :options="$get(deptListMaps, item.deptId, [])"
              :display-render="({ labels }) => labels.pop()"
              :field-names="{ label: 'name', value: 'id', children: 'children' }"
              :placeholder="item.deptId ? '请选择负责人' : '请选择部门'"
              style="width: 110px"
            />
            <span v-show="!item.editable">{{ text && text.length && $get(teacherMaps, `${text[text.length - 1]}.name`) || '无' }}</span> -->
          </template>
          <template slot="goods" slot-scope="text,item">
            <a-tree-select
              v-show="item.editable"
              v-model="item.goods"
              tree-default-expand-all
              show-search
              style="width: 100%"
              placeholder="请选择物资"
              allow-clear
              multiple
              :get-popup-container="getPopupContainer"
              search-placeholder="输入搜索物品名称"
              :filter-tree-node="filterTreeNode"
            >
              <a-tree-select-node
                v-for="fir in typeListTree"
                :key="`${fir.id}-${fir.name}`"
                :selectable="false"
                :value="fir.id"
                :title="fir.name"
              >
                <a-tree-select-node
                  v-for="sec in fir.children"
                  :key="`${fir.id}-${fir.name}-${sec.id}-${sec.name}`"
                  :selectable="false"
                  :value="sec.id"
                  :title="sec.name"
                >
                  <a-tree-select-node
                    v-for="thr in sec.children"
                    :key="`${fir.id}-${fir.name}-${sec.id}-${sec.name}-${thr.id}-${thr.name}`"
                    :value="thr.id"
                    :title="thr.name"
                  />
                </a-tree-select-node>
              </a-tree-select-node>
            </a-tree-select>
            <span v-show="!item.editable">{{ text ? text.join && text.map(i => $get(itemMaps, `${i}.name`)).join('，') : '无' }}</span>
          </template>
          <template slot="action" slot-scope="text,item">
            <div class="action-container">
              <span v-if="item.editable" class="success-link" @click="handleSave(item)">保存</span>
              <span v-else class="primary-link" @click="handleEdit(item)">编辑</span>
              <span class="primary-link" @click="handleDel(item)">删除</span>
            </div>
          </template>
        </a-table>
      </div>

      <div class="button-container">
        <a-button :loading="sending" class="success-btn" @click="handleSubmit">确定</a-button>
        <a-button class="danger-btn-border" @click="goback">取消</a-button>
      </div>
    </a-card>
  </page-view>
</template>

<script>
import { mapState } from 'vuex'
import { PageView } from '@/components'
import { uuid } from '@/utils/util'

export default {
  name: 'Add',
  inject: ['formItemLayout'],
  components: { PageView },
  props: {
    name: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    }
  },

  validate ({ params }) { return params.name },

  async fetch ({ store, app }) {
    const { dispatch } = store
    const list = [
      { fn: () => dispatch('property/getItemTypes') },
      { fn: () => dispatch('property/getItems') },
      { fn: app.$teacherListFunc }
    ]
    // if (!$get(store, 'state.basic.deptList.length')) list.push({ fn: app.$departmentListFunc })
    // if (!$get(store, 'state.basic.areaList.length')) list.push({ fn: app.$areaListFunc })
    await app.$requestList(list)
    dispatch('basic/setDeptArea')
  },

  async asyncData ({ app, $axios }) {
    const areaMaps = {}
    const areaList = await $axios.post('api/area/queryAll', { pid: 0 }).then(res => app.$get(res, 'data.data', [])).catch(e => [])
    areaList.forEach(i => {
      areaMaps[i.id] = i
    })
    return { areaList, areaMaps }
  },

  data () {
    return {
      sending: false,
      classSending: false,

      form: this.$form.createForm(this),

      columns: [
        { title: '序号', width: '85px', align: 'center', dataIndex: 'index' },
        { title: '盘点区域', width: '183px', align: 'center', dataIndex: 'deptId', scopedSlots: { customRender: 'deptId' }},
        { title: '负责人', width: '160px', align: 'center', dataIndex: 'userId', scopedSlots: { customRender: 'userId' }},
        { title: '盘点物资', align: 'center', dataIndex: 'goods', scopedSlots: { customRender: 'goods' }},
        { title: '操作', width: '112px', align: 'center', scopedSlots: { customRender: 'action' }}
      ],
      list: []
    }
  },

  computed: {
    ...mapState({
      itemMaps: state => state.property.itemMaps,
      typeListTree (state) {
        const { $clonedeep, $get } = this
        const { itemSecTypeListMaps, itemFirTypeList, itemListMaps } = state.property
        const list = $clonedeep(itemFirTypeList)
        list.forEach(fir => {
          fir.children = $get(itemSecTypeListMaps, `${fir.id}`, [])
            .map(sec => Object.assign(sec, { children: $get(itemListMaps, `${sec.id}`, []) }))
            .filter(sec => sec.children.length)
        })
        return list.filter(fir => fir.children.length && fir.children.filter(sec => sec.children.length).length)
      },
      // areaList: state => state.basic.areaList,
      // areaMaps: state => state.basic.areaMaps
      // deptAreaList: state => {
      //   const { deptListMaps = {}, areaListMaps = {}} = state.basic
      //   const list = []
      //   for (const deptId in deptListMaps) {
      //     const arr = deptListMaps[deptId] || []
      //     list.push(...arr.map(i => Object.assign({}, i, { children: areaListMaps[i.areaId] })))
      //   }
      //   return list
      // },
      // deptList: state => state.basic.deptList.filter(i => state.basic.deptListMaps[i.deptId]),
      // deptMaps: state => state.basic.deptMaps
      teacherMaps: state => state.basic.teacherMaps
      // deptListMaps (state) {
      //   const { $get, $clonedeep } = this
      //   const obj = $clonedeep(state.basic.deptListMaps)
      //   for (const id in obj) {
      //     const arr = obj[id]
      //     arr.forEach(i => {
      //       const { userId, userName, children } = i
      //       if (!$get(i, 'children.length')) Object.assign(i, { id: userId, name: userName })
      //       else children.forEach(c => Object.assign(c, { id: c.userId, name: c.userName }))
      //     })
      //   }
      //   return obj
      // }
    })
  },

  watch: {
    list (arr) {
      arr.forEach((i, k) => Object.assign(i, { index: k + 1 }))
    }
  },

  mounted () {
    const { name, id, $get, getTempData, list } = this
    const tempList = $get(getTempData(), `${name}${id}`, [])
    list.push(...tempList)
  },

  methods: {
    filterTreeNode (value, node) {
      return node.key.includes(value)
    },

    getPopupContainer () {
      return document.querySelector('.page-view')
    },

    getTempData () {
      if (!process.client) return {}
      return JSON.parse(sessionStorage.getItem('temp_new_plan_child') || '{}')
    },

    goback () {
      this.$router.go(-1)
    },

    handleEdit (item) {
      Object.assign(item, { editable: true })
      this.$forceUpdate()
    },

    handleSave (item) {
      Object.assign(item, { editable: undefined })
      this.$forceUpdate()
      if (process.client) {
        const tempData = this.getTempData()
        const tempList = tempData[this.name] || []
        const index = this.$findindex(tempList, i => i.id === item.id)
        if (index > -1) tempList.splice(index, 1, item)
        else tempList.push(item)
        tempList.sort((a, b) => a.index - b.index)
        tempData[`${this.name}${this.id}`] = tempList
        sessionStorage.setItem('temp_new_plan_child', JSON.stringify(tempData))
      }
    },

    handleDel (item) {
      const tempData = this.getTempData()
      const tempList = tempData[this.name] || []
      const index = this.$findindex(tempList, i => i.id === item.id)
      if (index > -1) {
        tempList.splice(index, 1)
        tempData[this.name] = tempList
        sessionStorage.setItem('temp_new_plan_child', JSON.stringify(tempData))
      }
      this.list.splice(item.index - 1, 1)
    },

    handleAdd () {
      this.list.push({ id: uuid(), deptId: undefined, userId: undefined, goods: undefined, editable: undefined })
      this.$forceUpdate()
    },

    handleSubmit () {
      const { $message, form, list, submit } = this
      form.validateFields((err, values) => {
        if (!err) {
          const notFinish = list.some(item => !item.deptId || !item.goods)
          $message.destroy()
          if (notFinish) $message.error('区域中数据不能为空')
          else submit(values)
        }
      })
    },

    async submit (values = {}) {
      const { id, $axios, $message, $get, goback, list, $moment, $clonedeep, areaMaps } = this
      const param = { ...values, status: 0, pid: id / 1 }
      param.assetsInventoryPlanDetailForm = $clonedeep(list).map(i => Object.assign(i, {
        index: undefined,
        id: undefined,
        userId: $get(areaMaps, `${i.deptId}.userId`),
        planId: id / 1,
        goods: i.goods.join(','),
        editable: undefined,
        status: 0,
        isDelete: 0
      }))
      param.deadline = `${$moment(param.deadline).format('YYYY-MM-DD')} 23:59:59`
      const code = await $axios.post('api/assetsInventoryPlan/', param).then(res => $get(res, 'data.code', -1)).catch(e => -1)
      $message.destroy()
      if (code !== '000000') return $message.error('请稍后再试')
      $message.info('新增成功')
      goback()
    }
  }
}
</script>

<style lang="less" scoped>
  .button-container {
    text-align: center;
    margin-top: 20px;
  }

  /deep/ .ant-select-dropdown.ant-select-tree-dropdown {
    max-height: 40vh !important;
  }
</style>
